$(function () {
    var cashier_dialog = $("#cashier_dialog");
    var cashier_datagrid = $("#cashier_datagrid");
    var product_datagrid = $("#product_datagrid");
    var cashier_form = $("#cashier_form");
    var client_datagrid = $("#client_datagrid");
    var ordersTable = $("#ordersTable");
    var methodObj = {
        //输入密码付款
        import_password:function(){
            var name = $("#clientName").textbox("getValue");
            var password = $("#password").textbox("getValue");
            $.post("/client/loginBysale.do", {"name": name , "password":password}, function (data) {
                if (data.success) {
                    $("#client_dialog").dialog("close");
                    $("#password").val("");
                    cashier_form.form("submit", {
                        url: '/sale/payment.do',
                        onSubmit: function (param) {
                            param["client.id"] = $("input[tag='clientId']").val();
                            param["depot.id"] = $("#depotId").combobox('getValue');
                            $.each($("#cashier_item tr"), function (index, item) {
                                param["items["+index+"].product.id"] = $(item).find("#productSn").val();
                                param["items["+index+"].product.name"] = $(item).find("#productName").val();
                                param["items["+index+"].salePrice"] = $(item).find("#salePrice").val();
                                param["items["+index+"].number"] = $(item).find("#number").val();
                            })
                        },
                        success: function (data) {
                            data = $.parseJSON(data);
                            if (data.success) {
                                $.messager.alert('温馨提示', "操作成功", 'info', function () {
                                    cashier_form.form('clear');
                                });
                            } else {
                                $.messager.alert('温馨提示', data.msg, 'error');
                            }
                        }
                    })
                } else {
                    $.messager.alert('温馨提示', data.msg, 'error');
                }
            }, "json")
        },
        //付款操作
        payment:function(){

            var item = $("#productName").val();
            if (item == ""){
                $.messager.alert('温馨提示', "请添加商品", 'error');
                return;
            }
            var number = $("#clientNumber").val();
            if (number == ""){
                $.messager.alert('温馨提示', "请添加会员", 'error');
                return;
            }
            var tr = $("#cashier_item tr")
            var amount = 0;
            for (var i = 0 ; i < tr.length ; i++){
                amount = parseFloat($(tr[i]).find("#amount").val()) + amount;
            }
            //判断卡内余额是否充足
            if ($("#balance").textbox("getValue") != ''){
                if(amount > $("#balance").textbox("getValue")){
                    $.messager.alert('温馨提示', "您的余额不足", 'error');
                    return
                }
            }
            //输入密码付款
            if ($("#clientName").textbox("getValue") != ''){
                $("#client_dialog").dialog("open");

            }
           /* cashier_form.form("submit", {
                url: '/sale/payment.do',
                onSubmit: function (param) {
                    param["client.id"] = $("input[tag='clientId']").val();
                    $.each($("#cashier_item tr"), function (index, item) {
                        param["items["+index+"].product.id"] = $(item).find("#productSn").val();
                        param["items["+index+"].product.name"] = $(item).find("#productName").val();
                        param["items["+index+"].salePrice"] = $(item).find("#salePrice").val();
                        param["items["+index+"].number"] = $(item).find("#number").val();
                    })
                },
                success: function (data) {
                    data = $.parseJSON(data);
                    if (data.success) {
                        $.messager.alert('温馨提示', "操作成功", 'info', function () {
                            cashier_form.form('clear');
                        });
                    } else {
                        $.messager.alert('温馨提示', data.msg, 'error');
                    }
                }
            })*/
        },
        //挂单操作
        entryOrders:function(){
            var item = $("#productName").val()
            var number = $("#clientNumber").val();
            if (item == ""){
                $.messager.alert('温馨提示', "请添加商品", 'error');
                return;
            }
            if (number == ""){
                $.messager.alert('温馨提示', "请添加会员", 'error');
                return;
            }


            $.messager.confirm('温馨提示', '您确定要挂单?', function (y) {
                if (y) {
                    cashier_form.form("submit", {
                        url: '/sale/hangBill.do',
                        onSubmit: function (param) {
                            param["client.id"] = $("input[tag='clientId']").val();
                            $.each($("#cashier_item tr") , function(index , item){
                                param["items["+index+"].product.id"] = $(item).find("#productSn").val();
                                param["items["+index+"].product.name"] = $(item).find("#productName").val();
                                param["items["+index+"].salePrice"] = $(item).find("#salePrice").val();
                                param["items["+index+"].number"] = $(item).find("#number").val();
                            })
                        },
                        success: function (data) {
                            data = $.parseJSON(data);
                            if (data.success) {
                                $.messager.alert('温馨提示', "挂单成功", 'info', function () {
                                    cashier_datagrid.datagrid("reload");
                                    window.location.href = "http://localhost/cashier/list.do"
                                });
                            } else {
                                $.messager.alert('温馨提示', "挂单失败", 'error');
                            }
                        }
                    })
                }
            })
        },
        //删除挂单
        remove:function(){
            var row = $("#ordersTable").datagrid("getSelected")
            if (!row) {
                $.messager.alert('温馨提示', '请选中一条数据!', 'warning');
                return;
            }
            var num = row.id
            $.messager.confirm('温馨提示', '您确定要删除该订单吗?', function (y) {
                if (y) {
                    $.get("/sale/delete.do", {id: num}, function (data) {
                        if (data.success) {
                            $.messager.alert('温馨提示', "操作成功", 'info');
                            $("#ordersTable").datagrid('reload');
                        } else {
                            $.messager.alert('温馨提示', data.msg, 'error');
                        }
                    }, "json")
                }
            });
        },
        //取出挂起的订单并删除此挂单
        save:function(){
            var row = $("#ordersTable").datagrid("getSelected")
            if (!row) {
                $.messager.alert('温馨提示', '请选中一条数据!', 'warning');
                return;
            }
            $("#clientName").textbox("setValue" , row.client.name);
            $("#clientNumber").textbox("setValue" , row.client.id);
            $("#balance").textbox("setValue" , row.client.balance);
            var items = row.items;
            for (var i = 0 ; i < items.length ; i++){
                if (i == 0){
                    $("#productSn").val(items[i].product.id);
                    $("#productName").val(items[i].product.name);
                    $("#salePrice").val(items[i].salePrice);
                    $("#number").val(items[i].number);
                    $("#amount").val(items[i].amount);
                } else {
                    var copy = $("#cashier_item tr:first").clone(true);
                    copy.find("#productSn").val(items[i].product.id);
                    copy.find("#productName").val(items[i].product.name);
                    copy.find("#salePrice").val(items[i].salePrice);
                    copy.find("#number").val(items[i].number);
                    copy.find("#amount").val(items[i].amount);
                    copy.appendTo($("#cashier_item"));
                }
            }
            var tr = $("#cashier_item tr")
            var amount = 0;
            if ($("#cashier_item tr:first" != '')){
                for (var i = 0 ; i < tr.length ; i++){
                    if ($(tr[i]).find("#amount").val() != ''){
                        amount = parseFloat($(tr[i]).find("#amount").val()) + amount;
                    }
                }
            }
            $("#totalNum").html("<font size='5'>"+amount+"</font>")
            $('#selectOrders').dialog("close")
            var num = row.client.id
            $.get("/cashier/delete.do", {id: num}, function (data) {
                if (data.success) {
                    $.messager.alert('温馨提示', "取单成功", 'info');
                } else {
                    $.messager.alert('温馨提示', "取单失败", 'error');
                }
            }, "json")
        },
        //取单
        selectOrders:function(){
            var name = $("#clientNumber").val()
            var item = $("#productName").val()
            if (item == "" || name==""){
                $('#selectOrders').dialog("open")
                ordersTable.datagrid("load")
            } else {
                $.messager.alert('温馨提示', '请结束当前订单', 'warning');
            }
        },
        //取消取单
        cancel:function(){
            $('#selectOrders').dialog("close")
        },

        reload: function () {
            cashier_datagrid.datagrid("reload");
        },
    }
    //事件统一绑定
    $("[data-cmd]").click(function () {
        var cmd = $(this).data("cmd");
        methodObj[cmd]();
    });
    //取单弹窗
    $('#selectOrders').dialog({
        title: '取单',
        width: 400,
        height: 300,
        buttons:"#cashier_btns",
        closed:true,

    });
    //取单表格
    $("#ordersTable").datagrid({
        url:'/sale/hangBillList.do',
        fitColumns:true,
        rownumbers:true,
        fit:true,
        scrollbarSize:0,
        singleSelect:true,
        columns:[[
            {
                field: 'client.id',
                title: '客户编号',
                width: 100,
                align:'center',
                formatter: function (value, row, index) {
                    return row.client? row.client.id : '';
                }
            },
            {
                field: 'client.name',
                title: '客户名称',
                width: 100,
                align:'center',
                formatter: function (value, row, index) {
                    return row.client? row.client.name : '';
                }
            }
        ]],
        //选中一行表单
        onClickRow:function(index , row){

        }
    });
    //会员信息页面
    client_datagrid.datagrid({
        fit:true,
        url: '/client/query.do',
        fitColumns: true,
        pagination: true,
        singleSelect: true,
        rownumbers: true,
        toolbar: '#client_toolbar',
        columns: [[
            {field: 'number', title: '卡号', width: 100},
            {field: 'name', title: '会员姓名', width: 100},
            {field: 'tel', title: '电话号码', width: 100},

            {field: 'level', title: '会员等级', width: 100},
            {field: 'integral', title: '可用积分', width: 100},
            {field: 'balance', title: '储值余额', width: 100},
            {field: 'address', title: '客户地址', width: 100}
        ]],
        //页面点击一行获取会员信息
        onClickRow: function (index, row) {
            $("#clientName").textbox("setValue" , row.name);
            $("#clientNumber").textbox("setValue" , row.number);
            $("#balance").textbox("setValue" , row.balance);
            $("input[tag='clientId']").val(row.id);
        }
    });
    //会员搜索
    $("#client_keyword").searchbox({
        searcher: function (value,name) {
            //重新加载数据表格,带上自定义查询参数
            client_datagrid.datagrid("load",{
                keyword:value
            });
        }
    });
    //商品高级查询
    $("#product_keyword").searchbox({
        searcher: function (value,name) {
            //重新加载数据表格,带上自定义查询参数
            cashier_datagrid.datagrid("load",{
                keyword:value
            });
        }
    });
    //商品信息页面
    cashier_datagrid.datagrid({
        url: '/product/query.do',
        fitColumns: true,
        pagination: true,
        singleSelect: true,
        rownumbers: true,
        toolbar: '#cashier_toolbar',
        columns: [[
            {field: 'name', title: '商品名', width: 100},
            {
                field: 'first', title: '一级分类', width: 100, formatter: function (value, row, index) {
                    return value ? value.name : "";
                }
            },
            {
                field: 'second', title: '二级分类', width: 100, formatter: function (value, row, index) {
                    return value ? value.classify : "";
                }
                //{
                //    field: 'headImg', title: '商品头像', width: 100,formatter:function(value, rec){
                //    return '<img src='+value+'/>';
                //
                //}
            },
            {field: 'sn', title: '商品编码', width: 100},
            {field: 'salePrice', title: '零售价', width: 100}
        ]],
        //点击一行时增加商品到收银明细
        onClickRow: function (index, row) {
            var trs = $("#cashier_item tr");
            var ids = $.map(trs , function(item){
                return $(item).find("#productName").val()
            })
            if (ids[0] == ''){
                var tr = $("#cashier_item tr:first")
                tr.find("#productSn").val(row.id);
                tr.find("#productName").val(row.name);
                tr.find("#salePrice").val(row.salePrice);
                var num = Number(tr.find("#number").val())
                tr.find("#number").val(num + 1);
                tr.find("#amount").val(row.salePrice);
                //$("#totalNum").html(row.salePrice)
            } else {
                $.each(ids , function(index , item){
                    if ($.inArray(row.name , ids) > -1){
                        var tr = $("#cashier_item tr")
                        for (var i = 0 ; i < tr.length ; i++){
                            if ($(tr[i]).find("#productSn").val() == row.id){
                                var num = Number($(tr[i]).find("#number").val())
                                $(tr[i]).find("#number").val(num + 1);
                                $(tr[i]).find("#amount").val((row.salePrice)*(num+1));
                                return false
                            }
                        }
                        tr.find("#amount").val(row.salePrice);
                    } else {
                        var copy = $("#cashier_item tr:first").clone(true);
                        copy.find("#productSn").val(row.id);
                        copy.find("#productName").val(row.name);
                        copy.find("#salePrice").val(row.salePrice);
                        copy.find("#number").val(1);
                        copy.find("#amount").val(row.salePrice);
                        copy.appendTo($("#cashier_item"));
                        return false;
                    }
                });
            }
            //计算总金额
            var tr = $("#cashier_item tr")
            var amount = 0;
            for (var i = 0 ; i < tr.length ; i++){
                if ($(tr[i]).find("#amount").val() != ''){
                    amount = parseFloat($(tr[i]).find("#amount").val()) + amount;
                }
            }

            $("#totalNum").html("<font size='5'>"+amount+"</font>")
        },
        view: detailview,
        detailFormatter: function (rowIndex, rowData) {
            return "<table><tr><td  width='100'><img src=" + rowData.headImg +
                " style='height:60px; width: 60px'></td>" +
                "<td width='200'>商品编码: " + rowData.sn + "</td>" +
                "<td width='200'>商品名称: " + rowData.name + "</td>" +
                "<td width='200'>商品售价: " + rowData.salePrice + "</td>" +
                "<td width='200'>会员折扣价: " + rowData.countPrice + "</td>" +
                "<td width='200'>商品简介: " + rowData.remark + "</td>" +
                "</tr></table>";
        }
    });
    //计算金额小计
    $("#cashier_item").on("blur" , "#salePrice , #number"  , function(){
        var currentTr = $(this).closest("tr");
        var salePrice = parseFloat(currentTr.find("#salePrice").val()) || 0;
        var number = parseFloat(currentTr.find("#number").val()) || 0;
        var amount = (salePrice * number).toFixed(2);
        currentTr.find("#amount").val(amount);
        var tr = $("#cashier_item tr")
        var amount = 0;
        for (var i = 0 ; i < tr.length ; i++){
            amount = parseFloat($(tr[i]).find("#amount").val()) + amount;
        }
        $("#totalNum").html("<font size='5'>"+amount+"</font>")
    }).on("click" , "#remove_item" , function (){ //删除商品信息
        var currentTr = $(this).closest("tr");
        if($("#cashier_item tr").size() > 1){
            currentTr.remove();
        } else {
            currentTr.find("#productSn").val("");
            currentTr.find("#productName").val("");
            currentTr.find("#salePrice").val("");
            currentTr.find("#number").val("");
            currentTr.find("#amount").val("");
        }
        var tr = $("#cashier_item tr")
        var amount = 0;
        if ($("#cashier_item tr:first" != '')){
            for (var i = 0 ; i < tr.length ; i++){
                if ($(tr[i]).find("#amount").val() != ''){
                    amount = parseFloat($(tr[i]).find("#amount").val()) + amount;
                }
            }
        }
        $("#totalNum").html("<font size='5'>"+amount+"</font>")
    });
});